package baiqitun.stupro.common.util.excel;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import org.springframework.lang.NonNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * Excel解析器抽象类
 * @author kedaji
 * @param <E>
 */
public abstract class AbstractExcelParser<E> implements ExcelParser<E>{
    @Override
    public E parse(@NonNull InputStream is){
        // 先创建临时文件
        File tempExcel = null;
        File dir = FileUtil.mkdir("/tmp");
        ExcelReader reader = null;
        try {
            tempExcel = FileUtil.createTempFile(dir);
            FileUtil.writeFromStream(is, tempExcel);
            reader = ExcelUtil.getReader(tempExcel);
            return executeReadAndConvert(reader);
        } finally {
            reader.close();
            FileUtil.del(dir);
        }
    }

    /**
     * 开始解析数据
     * @param reader ExcelReader
     * @return 读取到的数据
     */
    protected abstract E executeReadAndConvert(ExcelReader reader);
}
